package com.demo.day0308;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 图片下载组件
 */
@WebServlet(name = "FileDownloadServlet", urlPatterns = "/file")
public class FileDownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();

        //获取文件对象
        File file = new File("G:\\img.png");
        //获取输入流
        InputStream inputStream = new FileInputStream(file);
        //字节数据
        byte[] bys = new byte[1024];
        //通过响应 设置响应头 告诉浏览器 要下载文件
        response.setHeader("content-disposition", "attachment;fileName=" + new String("小明.png".getBytes("utf-8"), "ISO8859-1"));
        //实际接收的大小
        int len = 0;
        while ((len = inputStream.read(bys)) != -1) {
            outputStream.write(bys, 0, len);
            //刷新流
            outputStream.flush();
        }
        //关闭流
        inputStream.close();
        outputStream.close();
    }
}
